package app.server.project.main.service.db.dao.user;

import app.server.project.core.constants.Def;
import app.server.project.main.service.db.entity.user.UserRankEntity;
import app.server.project.main.service.db.mapper.user.UserRankEntityMapper;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Repository
public class UserRankDao extends ServiceImpl<UserRankEntityMapper, UserRankEntity> {

    //@Cacheable(key = "#userId+':'+#rankId", cacheNames = "app.server.project.main.service.db.dao.UserRankDao")
    public UserRankEntity getByIds(long userId, int rankId) {
        var data = this.getOne(Wrappers.lambdaQuery(UserRankEntity.class)
                .eq(UserRankEntity::getUserId, userId)
                .eq(UserRankEntity::getRankId, rankId));
        if (Objects.isNull(data)) {
            //缓存没有,就往库中写入一条数据
            data = UserRankEntity.of(userId, rankId, IdUtil.getSnowflakeNextId());
        }
        data.setSynDb(true);
        return data;
    }

    public List<UserRankEntity> getRankByRankId(int rankId, int size) {
        return this.page(Page.of(Def.Zero, size),
                        Wrappers.<UserRankEntity>lambdaQuery()
                                .eq(UserRankEntity::getRankId, rankId)
                                .ne(UserRankEntity::getVal, Def.Zero)
                                .orderByDesc(UserRankEntity::getVal))
                .getRecords();
    }


    public synchronized void reset(int rankId) {
        this.update(Wrappers.<UserRankEntity>lambdaUpdate()
                .ne(UserRankEntity::getVal, Def.Zero)
                .eq(UserRankEntity::getRankId, rankId)
                .set(UserRankEntity::getVal, Def.Zero)
                .set(UserRankEntity::getCreateTime, LocalDateTime.now()));
    }
}
